package com.fac.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fac.entity.Equipment;
import com.fac.entity.RepairOrder;
import com.fac.mapper.EquipmentMapper;
import com.fac.mapper.LeaseOrderMapper;
import com.fac.mapper.RepairOrderMapper;
import com.fac.mapper.PaymentRecordMapper;
import com.fac.service.StatisticsService;
import com.fac.vo.EquipmentUsageVO;
import com.fac.vo.IncomeStatVO;
import com.fac.vo.MaintenanceStatVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StatisticsServiceImpl implements StatisticsService {
    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    private RepairOrderMapper repairOrderMapper;
    @Autowired
    private LeaseOrderMapper leaseOrderMapper;
    @Autowired
    private PaymentRecordMapper paymentRecordMapper;

    @Override
    public EquipmentUsageVO getEquipmentUsage(LocalDate startDate, LocalDate endDate) {
        log.info("获取设备使用统计, startDate: {}, endDate: {}", startDate, endDate);

        // 获取设备总数和各状态数量
        List<Equipment> equipmentList = equipmentMapper.selectList(Wrappers.lambdaQuery());
        Map<Integer, Long> statusCounts = equipmentList.stream()
                .collect(Collectors.groupingBy(e -> e.getStatus().getValue(), Collectors.counting()));

        // 计算总数
        long total = equipmentList.size();

        // 获取各状态数量
        // 使用中
        long inUse = statusCounts.getOrDefault(1, 0L);
        // 维修中
        long maintenance = statusCounts.getOrDefault(2, 0L);
        // 闲置
        long idle = statusCounts.getOrDefault(0, 0L);

        // 计算使用率
        double usageRate = total > 0 ? (double) inUse / total : 0;

        // 获取分类使用情况
        List<EquipmentUsageVO.CategoryUsage> categoryUsages = equipmentMapper.getCategoryUsageStats();

        return EquipmentUsageVO.builder()
                .totalEquipment((int) total)
                .inUseCount((int) inUse)
                .maintenanceCount((int) maintenance)
                .idleCount((int) idle)
                .usageRate(usageRate)
                .categoryUsage(categoryUsages)
                .build();
    }

    @Override
    public MaintenanceStatVO getMaintenanceStats(LocalDate startDate, LocalDate endDate) {
        log.info("获取维修统计, startDate: {}, endDate: {}", startDate, endDate);

        // 获取维修订单统计
        List<RepairOrder> orders = repairOrderMapper.selectByDateRange(startDate, endDate);

        // 计算订单总数和完成数
        int totalOrders = orders.size();
        int completedOrders = (int) orders.stream()
                // 状态为已完成
                .filter(o -> o.getStatus() == 2)
                .count();

        // 计算平均维修时间（小时）
        double avgRepairTime = orders.stream()
                .filter(o -> o.getFinishTime() != null && o.getStartTime() != null)
                .mapToLong(o -> ChronoUnit.HOURS.between(o.getStartTime(), o.getFinishTime()))
                .average()
                .orElse(0);

        // 计算总维修费用
        BigDecimal totalRepairFee = orders.stream()
                .map(RepairOrder::getRepairFee)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 获取设备故障排名
        List<MaintenanceStatVO.EquipmentRanking> rankings = repairOrderMapper.getEquipmentFaultRanking(startDate, endDate);

        return MaintenanceStatVO.builder()
                .totalOrders(totalOrders)
                .completedOrders(completedOrders)
                .avgRepairTime((int) avgRepairTime)
                .totalRepairFee(totalRepairFee)
                .equipmentRanking(rankings)
                .build();
    }

    @Override
    public IncomeStatVO getIncomeStats(LocalDate startDate, LocalDate endDate) {
        log.info("获取收入统计, startDate: {}, endDate: {}", startDate, endDate);

        // 获取租赁收入
        BigDecimal leaseIncome = paymentRecordMapper.getIncomeByTypeAndDateRange(
                "租赁单", "租金", startDate, endDate);

        // 获取维修收入
        BigDecimal maintenanceIncome = paymentRecordMapper.getIncomeByTypeAndDateRange(
                "维修单", "维修费", startDate, endDate);

        // 获取每日收入
        List<IncomeStatVO.DailyIncome> dailyIncomes = paymentRecordMapper.getDailyIncome(startDate, endDate);

        // 获取分类收入
        List<IncomeStatVO.CategoryIncome> categoryIncomes = paymentRecordMapper.getCategoryIncome(startDate, endDate);

        // 计算总收入
        BigDecimal totalIncome = leaseIncome.add(maintenanceIncome);

        return IncomeStatVO.builder()
                .totalIncome(totalIncome)
                .leaseIncome(leaseIncome)
                .maintenanceIncome(maintenanceIncome)
                .dailyIncome(dailyIncomes)
                .categoryIncome(categoryIncomes)
                .build();
    }
} 